package com.arqui.admmon_module.client.core.main;

import com.arqui.admmon_module.client.action.GetLogin;
import com.arqui.admmon_module.client.action.GetLoginResult;
import com.arqui.admmon_module.client.place.NameTokens;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.shared.DispatchAsync;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class LoggingPresenter extends
		Presenter<LoggingPresenter.MyView, LoggingPresenter.MyProxy> {
	
	@Inject	PlaceManager placeManager;
	@Inject	DispatchAsync dispatcher;
	
	public interface MyView extends View {
		
		public Label getUsuarioLabel();

		public Label getContraseniaLabel();

		public TextBox getUsuarioTextBox();

		public PasswordTextBox getContraseniaPasswordBox();

		public Button getInicioButton();
		
		public Label getMensajeLabel();
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.logging)
	public interface MyProxy extends ProxyPlace<LoggingPresenter> {
	}
	
	@Inject
	public LoggingPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy) {
		super(eventBus, view, proxy);
	}
	
	@Override
	protected void revealInParent() {
		RevealRootContentEvent.fire(this, this);
	}

	@Override
	protected void onBind() {
		super.onBind();
	}

	@Override
	protected void onReset() {
		super.onReset();
		
		getView().getInicioButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				GetLogin action = new GetLogin(getView().getUsuarioTextBox().getText(),getView().getContraseniaPasswordBox().getText());
				dispatcher.execute(action,loginCallBack);
			}
		});
	}
	
	private AsyncCallback<GetLoginResult> loginCallBack = new AsyncCallback<GetLoginResult>() {
		@Override
		public void onSuccess(GetLoginResult result) {
			if(result.getState()){
				PlaceRequest request = new PlaceRequest(NameTokens.main);
				placeManager.revealPlace(request);
			}else{
				getView().getMensajeLabel().setText(result.getMessage());
			}
		}
		
		@Override
		public void onFailure(Throwable caught) {
			getView().getMensajeLabel().setText("Lo sentimos, Ocurrio un error inesperado");
			}
		
	};

}
